package city.spring.modules.system.controller;

import city.spring.modules.system.dto.MenuViewDTO;
import city.spring.modules.system.entity.MenuEntity;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.enums.SiteType;
import city.spring.modules.system.service.MenuService;
import city.spring.modules.system.service.UserService;
import city.spring.modules.work.service.WorkScheduleService;
import city.spring.utils.UserUtils;
import com.baomidou.mybatisplus.extension.api.ApiController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 当前登录用户信息
 *
 * @author HouKunLin
 * @date 2020/1/5 0005 1:25
 */
@RestController
public class CurrentUserController extends ApiController {
    private static final Logger logger = LoggerFactory.getLogger(CurrentUserController.class);
    private final UserService userService;
    private final MenuService menuService;
    private final WorkScheduleService scheduleService;

    public CurrentUserController(UserService userService, MenuService menuService, WorkScheduleService scheduleService) {
        this.userService = userService;
        this.menuService = menuService;
        this.scheduleService = scheduleService;
    }

    /**
     * 获取当前登录用户信息
     *
     * @param user 当前登录用户
     * @return 用户信息
     */
    @RequestMapping("/currentUser")
    public Object currentUser() {
        return UserUtils.getUser();
    }

    /**
     * 获取当前登录用户的菜单信息
     *
     * @param user 当前登录用户
     * @param site 站点菜单类型：1 机构养老菜单（默认），2 护士站菜单（特殊菜单）
     * @return 用户的菜单列表信息
     */
    @RequestMapping("/currentUser/menu")
    public Object currentUserMenu(@RequestParam(required = false, defaultValue = "1") Integer site) {
        UserEntity userEntity = UserUtils.getUser();
        SiteType type = SiteType.create(site);
        if (type == SiteType.NONE) {
            return success(Collections.emptyList());
        }
        List<MenuViewDTO> allMenuView = menuService.getAllMenuView();
        List<MenuViewDTO> siteMenuViews = allMenuView.stream()
                .filter(item -> site.equals(item.getSite()))
                .collect(Collectors.toList());

        List<MenuViewDTO> menuList = menuService.filterUserMenuList(userEntity, siteMenuViews);
        // 对整体进行排序
        menuList.sort((e1, e2) -> {
            int n1 = 0;
            int n2 = 0;
            if (e1.getIsShow() != null && e1.getIsShow()) {
                n1 = 1;
            }
            if (e2.getIsShow() != null && e2.getIsShow()) {
                n2 = 1;
            }
            if (n1 == n2) {
                return e1.getSorted() - e2.getSorted();
            } else {
                // 展示按照倒序，从大到小，可以显示的放在前面
                return n2 - n1;
            }
        });
        List<MenuEntity> entities = menuService.converterToTreeDatasource(menuList);
        return success(entities);
    }

    /**
     * 获取 OAuth2 登录用户信息
     * <p>传入参数类型 Principal 实际上为 OAuth2Authentication 对象</p>
     * <p>传入参数类型 Authentication 实际上为 OAuth2Authentication 对象</p>
     *
     * @param user 用户信息
     * @return 信息
     */
    @RequestMapping("/principal")
    public Principal principal(Principal user) {
        return user;
    }

    /**
     * 设置当前登录用户的头像信息
     *
     * @param user 当前登录用户
     */
    @PostMapping("currentUser/setAvatar")
    public Object updateUserAvatar(Principal user, String avatarUrl) {
        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());
        userEntity.setAvatar(avatarUrl);
        userService.lambdaUpdate()
                .set(UserEntity::getAvatar, avatarUrl)
                .eq(UserEntity::getId, userEntity.getId())
                .update();

        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 修改当前登录用户信息
     *
     * @param user   当前登录用户
     * @param entity 新的用户信息
     */
    @PutMapping("currentUser/updateUserInfo")
    public Object updateUserInfo(Principal user, @RequestBody UserEntity entity) {
        UserEntity userEntity = userService.getUserByIdOrAccount(user.getName());

        UserEntity newUserEntity = new UserEntity();
        newUserEntity.setId(userEntity.getId());
        newUserEntity.setNickname(entity.getNickname());
        newUserEntity.setPhone(entity.getPhone());
        newUserEntity.setEmail(entity.getEmail());
        newUserEntity.setUsername(entity.getUsername());
        userService.saveOrUpdateBaseInfo(newUserEntity);

        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取当前登录用户的值班表
     *
     * @param user    当前登录用户
     * @param date    查询的日期
     * @param history 是否加载历史值班表
     * @return the work table
     */
    @GetMapping("currentUser/work-table")
    public Object getWorkTable(Principal user, @RequestParam(required = false) LocalDate date,
                               @RequestParam(required = false, defaultValue = "false") boolean history) {
        return success(scheduleService.getUserWorkSchedule(user.getName(), date, history));
    }
}
